﻿using ERPSystem.Common.Domains.UserCommon;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;
using NPOI.SS.Formula.Functions;

namespace RBACCommon.API.Command.UserEmail
{
    public class UserEmailLoginHandler : IRequestHandler<UserEmailLoginCommand, Result>
    {
        private readonly IBaseRepository<User> _userRepository;

        public UserEmailLoginHandler(IBaseRepository<User> userRepository)
        {
            _userRepository = userRepository;
        }

        public async Task<Result> Handle(UserEmailLoginCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            var list = await (await _userRepository.GetAll()).Where(x => x.Email == request.Email).ToListAsync();
            if (list.Count > 0)
            {
                list = list.Where(x => x.Code == request.Code).ToList();
                if (list.Count > 0)
                {
                    list = list.Where(x => DateTime.Now - x.CreateTime < TimeSpan.FromSeconds(60)).ToList();
                    if (list.Count > 0)
                    {
                        result.Data = list;
                        result.Msg = "邮箱登录成功";
                        result.Code = 1;
                    }
                    else
                    {
                        result.Code = -2;
                        result.Msg = "验证码已过期，请重新获取验证码";
                    }
                }
                else
                {
                    result.Code = -1;
                    result.Msg = "验证码错误";
                }
            }
            return result;

        }
    }
}
